package com.sec.android.app.myfiles.facade.cmd;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.dialog.EditTextDialogFragment;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.module.shortcut.ShortcutUtils;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.operation.FileOperationArgs;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.operation.ProgressListener;
import com.sec.android.app.myfiles.util.UiUtils;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

public class RenameRecordCmd extends SimpleCommand implements EditTextDialogFragment.EditTextCallback, ProgressListener {

    private EditTextDialogFragment mEditDialog;
    private FileOperator mFileOperator;
    private FileRecord mFileRecord;
    private FileRecord mDstRecord;
    AbsMyFilesFragment mFileListFragment;
    private Context mContext;
    private String mOriginalExt;
    private String mReservedName;
    private boolean defaultStateOfOk = false;
    private boolean mIsShortcutRecord = false;

    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();

        mContext = (Context) params[0];
        mFileListFragment = (AbsMyFilesFragment) params[1];
        mFileRecord = (FileRecord) params[2];
        mReservedName = (String) params[3];

        mIsShortcutRecord = ShortcutUtils.isExistFromShortcut(mContext, mFileRecord);

        int nTitleRes = R.string.menu_rename_file_title;
        if (mFileRecord.isDirectory()) {
            nTitleRes = R.string.menu_rename_folder_title;
        }

        mFileOperator = new FileOperator(mFileListFragment.getProcessId(), mContext, mFileListFragment.getFragmentManager(), null);
        mFileOperator.registerProgressListener(this, null);
        String name = mFileRecord.getName();
        boolean isExceedInputLength = false;
        String reservedExt = "";

        mOriginalExt = "";
        if (!mFileRecord.isDirectory()) {
            mOriginalExt = getExtWithDot(name);
        }

        if (mReservedName != null) {
            if (!mFileRecord.isDirectory()) {
                reservedExt = getExtWithDot(mReservedName);
                if (TextUtils.isEmpty(reservedExt)) {
                    name = mReservedName + mOriginalExt;
                } else {
                    name = mReservedName;
                }
            } else {
                name = mReservedName;
            }
        }

        if (name.length() > AppConstants.MAX_INPUT_LENGTH) {
            if (mReservedName != null) {
                name = name.substring(0, AppConstants.MAX_INPUT_LENGTH - reservedExt.length()) + reservedExt;
            } else {
                name = name.substring(0, AppConstants.MAX_INPUT_LENGTH - mOriginalExt.length()) + mOriginalExt;
            }
            isExceedInputLength = true;
        }

        int initialSelectionPos = mFileRecord.isDirectory() || (mReservedName != null && !mOriginalExt.equals(reservedExt)) ?
                name.length() : getNameWithoutExt(name).length();

        mEditDialog = new EditTextDialogFragment.Builder()
                .setEditTextCallback(this)
                .setTitle(nTitleRes)
                .setOkText(R.string.menu_rename)
                .setDefaultText(name)
                .setInitialSelectionPosition(initialSelectionPos)
                .setExceedInputLength(isExceedInputLength)
                .setInitialStateOfOk(defaultStateOfOk)
                .build();

        mEditDialog.show(mFileListFragment.getFragmentManager());
    }

    private String getExtWithDot(String fileName) {
        String ext = "";
        int index = fileName.lastIndexOf('.');
        if (index > 0) {
            ext = fileName.substring(index);
        }
        return ext;
    }

    private String getNameWithoutExt(String fileName) {
        String ret = fileName;
        int index = fileName.lastIndexOf('.');
        if (index > 0) {
            ret = fileName.substring(0, index);
        }
        return ret;
    }

    public static FileRecord getRenamedRecord(FileRecord fileRecord, String inputString) {
        String renamePath = fileRecord.getPath() + "/" + inputString;
        FileRecord ret = FileRecord.createFileRecord(fileRecord.getStorageType(), renamePath);
        if (ret != null && (fileRecord.getStorageType() == StorageType.Cloud)) {
            ((CloudFileRecord) ret).setDeviceId(((CloudFileRecord) fileRecord).getDeviceId());
            ((CloudFileRecord) ret).setParentId(((CloudFileRecord) fileRecord).getParentId());
        }
        return ret;
    }

    @Override
    public boolean checkNameExist(String inputString) {
        boolean bRet = false;
        if (mEditDialog != null && !TextUtils.isEmpty(inputString)) {
            FileRecord record = getRenamedRecord(mFileRecord, inputString);
            if (record != null && record.exists(mContext)) {
                bRet = true;
            }
        }
        return bRet;
    }

    @Override
    public boolean checkText(String inputString, Activity activity) {
        boolean bRet = true;
        if (mEditDialog != null && !TextUtils.isEmpty(inputString)) {
            FileRecord record = getRenamedRecord(mFileRecord, inputString);
            if (inputString != null && (inputString.equals(".") || inputString.equals(".."))) {
                mEditDialog.setInputErrorEnabled(true);
                if (record != null && record.isDirectory()) {
                    mEditDialog.setInputError(activity.getString(R.string.folder_name_invalid_characters));
                } else {
                    mEditDialog.setInputError(activity.getString(R.string.file_name_invalid_characters));
                }
                bRet = false;
            } else if (record != null && record.exists(activity)) {
                int nMsgRes = R.string.file_name_exist;
                if (record.isDirectory()) {
                    nMsgRes = R.string.folder_name_exist;
                }
                mEditDialog.setInputErrorEnabled(true);
                mEditDialog.setInputError(activity.getString(nMsgRes));
                bRet = false;
            } else if (!mFileRecord.isDirectory() && isExtOnly(inputString)) {
                mEditDialog.setInputErrorEnabled(true);
                mEditDialog.setInputError(activity.getString(R.string.file_name_is_empty));
                bRet = false;
            }
        }
        return bRet;
    }

    @Override
    public void onOK(String inputString, Activity activity) {
        if (checkText(inputString, activity)) {
            if (mEditDialog != null && !mFileRecord.isDirectory() && isExtChanged(inputString) && !isExtOnly(inputString)) {
                mEditDialog.dismiss();
                mEditDialog = null;
                showConfirmDialog(activity, inputString);
            } else {
                mDstRecord = getRenamedRecord(mFileRecord, inputString);
                FileOperationArgs args = new FileOperationArgs();
                args.mProcessId = mFileListFragment.getProcessId();
                args.mSrc = mFileRecord;
                args.mDst = mDstRecord;
                mFileOperator.setOperationArgs(FileOperator.Operation.RENAME, args);
                mFileOperator.execute();
                if (mEditDialog != null) {
                    mEditDialog.dismiss();
                }
                mFileListFragment.finishActionMode();
                MyFilesFacade.execSpinnerProgress(mFileListFragment.mProcessId, mContext, SpinnerProgressCmd.OperationProgress.SHOW);
            }

            SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.RENAME_POPUP, SamsungAnalyticsLog.Event.RENAME, null);
        }
    }

    @Override
    public void onCancel(Activity activity) {
        SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.RENAME_POPUP, SamsungAnalyticsLog.Event.CANCEL, null);
    }

    @Override
    public void onFinished(boolean bRet, String msg, Bundle extras) {
        //Remove below code temporarily
        //MyFilesFacade.reload(mFileListFragment.getProcessId(), mContext, mFileRecord.getParent(), mFileListFragment);
        MyFilesFacade.execSpinnerProgress(mFileListFragment.mProcessId, mContext, SpinnerProgressCmd.OperationProgress.DISMISS);
        if (bRet) {
            MyFilesFacade.renameHomeItem(mFileListFragment.getProcessId(), mContext, mFileRecord, mDstRecord);
        }

        if (AppFeatures.isTabletUIMode()) {
            if (mFileRecord.isDirectory()) {
                UiUtils.sendLocalBroadcastIntent(mContext, AppConstants.MYFILES_ACTION_FOLDER_DELETED, -1);
            }
        }

        NavigationInfo naviInfo = mFileListFragment.getNavigationInfo();
        if (naviInfo != null) {
            naviInfo.setFocusRecord(mDstRecord);
        }
        if (!TextUtils.isEmpty(msg)) {
            Toast.makeText(mContext, msg, bRet ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show();
        } else if (mIsShortcutRecord) {
            Toast.makeText(mContext, R.string.shortcut_removed, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onProgressChanged(String fileName, int progress, int total) {
        // DON'T need IMPLEMENT
    }

    private void showConfirmDialog(final Activity activity, final String renamedFile) {
        new AlertDialog.Builder(activity)
                .setTitle(R.string.change_file_extension)
                .setMessage(R.string.warning_for_extension_change)
                .setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onOK(renamedFile, activity);
                        SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.RENAME_POPUP, SamsungAnalyticsLog.Event.CHANGE, null);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        onCancel(activity);
                        SamsungAnalyticsLog.sendLog(SamsungAnalyticsLog.ScreenPath.RENAME_POPUP, SamsungAnalyticsLog.Event.RENAME_CANCEL_CHANGING_EXTESION, null);
                    }
                }).create().show();
    }

    private boolean isExtOnly(String inputString) {
        int index = inputString.indexOf('.');
        int lastIndex = inputString.lastIndexOf('.');

        return index == 0 ? index == lastIndex : false;
    }

    private boolean isExtChanged(String inputString) {
        boolean ret = true;
        int index = inputString.lastIndexOf('.');

        if (index > 0) {
            String renamedExt = inputString.substring(index);
            ret = !(mOriginalExt.equals(renamedExt));
        } else if (index == -1 && TextUtils.isEmpty(mOriginalExt)) {
            ret = false;
        }
        return ret;
    }
}
